#初始化

import os
from utils.StandardSqlite3DB import SQLiteDB
import shutil
import numpy as np
from config import *
from colorama import Fore, Style
import colorama


colorama.init(autoreset=True)

## 创建文件夹（如果不存在）
def create_folder(path):
    folder_path = f'{path}'
    if not os.path.exists(folder_path):
        os.makedirs(folder_path)
        print(f"文件夹 '{folder_path}' 创建成功！")
    else:
        print(f"文件夹 '{folder_path}' 已存在。")


#实时分贝数据表
def create_table(time):
    table_name = 'db_table' + time
    SQLiteDB('data/fenbei_monitor.db').create_table(table_name,{"id" :'integer NOT NULL PRIMARY KEY AUTOINCREMENT',"time" :'text',"db": 'TEXT'})


# report源数据表countxx初始化
def creat_clear_table_count(recod_path):
    db = SQLiteDB('data/fenbei_monitor.db')
    res = db.execute(f'DROP TABLE IF EXISTS count_{recod_path}')
    print(res)
    res  = db.execute(f"""CREATE TABLE IF NOT EXISTS  count_{recod_path} ( "id" 'integer NOT NULL PRIMARY KEY AUTOINCREMENT',"time" 'text',"count" 'integer')  """)
    print(res)


# 获取当前目录所在磁盘的使用情况
def check_disk():
    usage = shutil.disk_usage(".")
    print(f"{Fore.GREEN}总空间: {usage.total / (1024 ** 3):.2f} GB / 剩余空间: {usage.free / (1024 ** 3):.2f} GB  /  10h消耗空间：~3GB")
    if usage.free  <3 * (1024 ** 3):
        exit('空闲空间不足,退出')


# 录音测试
def check_mic():
    try:
        p = pyaudio.PyAudio()
        default_input = p.get_default_input_device_info()
        print(f"{Fore.GREEN}默认麦克风: device_id:{default_input['index']}, {default_input['name']}")
        print(f"{Fore.GREEN}采样率: {default_input['defaultSampleRate']} Hz")

        # 录制 3 秒音频测试
        duration = 3
        sample_rate = int(default_input['defaultSampleRate'])
        chunk = 1024
        stream = p.open(format=pyaudio.paFloat32,
                        channels=CHANNELS,
                        rate=RATE,
                        input=True,
                        frames_per_buffer=CHUNK,
                        input_device_index=device_id,  # 指定设备 index值
                        )
        print("\n正在 3秒音频测试录音... 请说话...")
        frames = []
        for _ in range(0, int(sample_rate / chunk * duration)):
            data = stream.read(chunk)
            frames.append(np.frombuffer(data, dtype=np.float32))

        stream.stop_stream()
        stream.close()
        p.terminate()

        # 检查是否录到声音
        audio_data = np.concatenate(frames)
        max_volume = np.max(np.abs(audio_data))
        print( max_volume)
        if max_volume > 0.01:
            print("✅ 麦克风正常，检测到声音！")
        else:
            exit("⚠️ 麦克风可能无输入，请检查是否静音或未连接。")

    except Exception as e:
        exit(f"❌ 麦克风检测失败: {e}")



if __name__ == '__main__':
    print('init.py')